<?php
namespace app\api\controller;
use app\api\model\Bonus;
use app\api\model\BonusUsers;
use app\api\model\Config;
use think\Controller;
use think\Request;
use app\api\model\Pickup;
use app\api\model\Order;
use app\api\model\Pickupstock;
use app\api\model\Splicing;
use app\api\model\Splicingorder;
use app\api\model\Users;

/**
 * 骑手控制器基类
 */
class Rider extends Controller
{
    /**
     * 无需登录的方法
     * @var array
     */
    protected $noNeedLogin = [];
    /**
     * 默认响应输出类型,支持json/xml
     * @var string
     */
    protected $responseType = 'json';
    /**
     * @var array
     * 用户信息
     */
    protected $userInfo = [];//用户信息
    /**
     * 初始化操作
     * @access protected
     */
    protected function _initialize()
    {
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept,Token");
        header('Access-Control-Allow-Methods: GET,POST,PUT,OPTIONS');

        //判断token存在的时候返回true，否则未false
        $token = request()->header('token');
        if (!$this->match($this->noNeedLogin)) {
            if ($token) {
                $userInfo = db('rider')->where(['token' => $token])->find();
                if ($userInfo) {
                    $this->userInfo = $userInfo;
                } else {
                    return_msg(101,'登录已过期,请重新登录');
                }
            } else {
                return_msg(101,'未登录,请您登录');
            }
        } else{
            if ($token) {
                $userInfo = db('rider')->where(['token' => $token])->find();
                if ($userInfo) {
                    $this->userInfo = $userInfo;
                } else {
                    return_msg(101,'登录已过期,请重新登录');
                }
            }
        }

        if(!defined('UID')) {
            define('UID', 0);
        }
    }


    /**
     * 检测当前控制器和方法是否匹配传递的数组
     *
     * @param array $arr 需要验证权限的数组
     * @return boolean
     */
    public function match($arr = [])
    {
        $request = Request::instance();
        $arr = is_array($arr) ? $arr : explode(',', $arr);
        if (!$arr) {
            return FALSE;
        }
        $arr = array_map('strtolower', $arr);
        // 是否存在
        if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
            return TRUE;
        }
        // 没找到匹配
        return FALSE;
    }

    //自提验单列表
    public function rider_pickup_list(){
        //取餐点ID
        $pickup_id = input('pickup_id',0);  //取餐点ID
        $pickup = Pickup::where(['id'=>$pickup_id])->field('id,name,address,lat,lng,posts_num,fan_num,mian_num,tang_num')->find();
        if(empty($pickup)){
            return_msg(1,'参数错误,取餐点不存在');
        }
        //查询当天未取餐订单
        $where['o.order_status'] = '1';
        $where['o.pickup_id'] = $pickup_id;
        $where['o.date'] = date("Y-m-d");
        $field = "o.id,o.order_sn,o.num,o.aux,u.nickname,u.phone";
        $list = Order::alias('o')
            ->join('users u','u.id=o.users_id')
            ->where($where)
            ->field($field)
            ->order("o.id desc")
            ->select();
        $posts_num = $fan_num = $mian_num = $tang_num = 0;
        foreach($list as &$v){
            $posts_num += $v['num'];
            //查询 面、饭、汤 份数
            $v['fan_num'] = 0;
            $v['mian_num'] = 0;
            $v['tang_num'] = 0;
            $aux = json_decode($v['aux'],true);
            foreach($aux as $v2){
                foreach($v2 as $v3){
                    switch ($v3['id']){
                        case 1:
                            $v['tang_num'] += 1;
                            break;
                        case 2:
                            $v['mian_num'] += 1;
                            break;
                        case 3:
                            $v['fan_num'] += 1;
                            break;
                    }

                }
            }
            $fan_num += $v['fan_num'];
            $mian_num += $v['mian_num'];
            $tang_num += $v['tang_num'];
            unset($v['aux']);
        }

        $need_posts_num = $posts_num-$pickup['posts_num']>0?$posts_num-$pickup['posts_num']:0;
        $need_fan_num   = $fan_num-$pickup['fan_num']>0?$posts_num-$pickup['fan_num']:0;
        $need_mian_num  = $mian_num-$pickup['mian_num']>0?$posts_num-$pickup['mian_num']:0;
        $need_tang_num  = $tang_num-$pickup['tang_num']>0?$posts_num-$pickup['tang_num']:0;
        $return = [
            'pick_name'    =>  $pickup['name'],
            'no_meal'   =>  [
                'posts_num'     =>      $posts_num,
                'fan_num'       =>      $fan_num,
                'mian_num'      =>      $mian_num,
                'tang_num'      =>      $tang_num
            ],//未取餐
            'stock'     =>  [
                'posts_num'     =>      $pickup['posts_num'],
                'fan_num'       =>      $pickup['fan_num'],
                'mian_num'      =>      $pickup['mian_num'],
                'tang_num'      =>      $pickup['tang_num']
            ],//库存
            'need_sup'  =>  [
                'posts_num'     =>      $need_posts_num,
                'fan_num'       =>      $need_fan_num,
                'mian_num'      =>      $need_mian_num,
                'tang_num'      =>      $need_tang_num
            ],//需补餐
            'list'      =>  $list
        ];
        return_msg(0,'查询成功',$return);
    }

    //增加库存
    public function add_stock(){
        $pickup_id = input('pickup_id',0);  //取餐点ID
        $posts_num = input('posts_num',0);  //菜品数
        $fan_num = input('fan_num',0);      //米饭数
        $mian_num = input('mian_num',0);    //面条数
        $tang_num = input('tang_num',0);    //例汤数
        if(empty($pickup_id)){
            return_msg(1,'参数错误,取餐点不存在');
        }
        Pickup::where(['id'=>$pickup_id])->setInc('posts_num',$posts_num);
        Pickup::where(['id'=>$pickup_id])->setInc('fan_num',$fan_num);
        Pickup::where(['id'=>$pickup_id])->setInc('mian_num',$mian_num);
        Pickup::where(['id'=>$pickup_id])->setInc('tang_num',$tang_num);
        //生成记录
        $addData = [
            'pickup_id'         =>      $pickup_id,
            'posts_num'         =>      $posts_num,
            'fan_num'           =>      $fan_num,
            'mian_num'          =>      $mian_num,
            'tang_num'          =>      $tang_num,
            'desc'              =>      '骑手增加库存',
            'type'              =>      1,
            'usersid'           =>      $this->userInfo['id']
        ];
        Pickupstock::insert($addData);
        return_msg(0,'操作成功');
    }

    //自提订单核销
    public function write_off(){
        $order_sn = input('order_sn','');//订单号
        $field = "id,users_id,order_sn,order_status,money,time,pickup_id,num,aux,addtime";
        $order = Order::where(['order_sn'=>$order_sn])->field($field)->find();
        if(empty($order)){
            return_msg(1,'订单不存在！');
        }
        if($order['order_status'] == 0){
            return_msg(1,'未查询到该订单！');
        }
        if($order['order_status'] == 2){
            return_msg(1,'该订单已取餐！');
        }
        $fan_num = $mian_num = $tang_num = 0;
        $aux = json_decode($order['aux'],true);
        foreach($aux as $v2){
            foreach($v2 as $v3){
                switch ($v3['id']){
                    case 1:
                        $tang_num += 1;
                        break;
                    case 2:
                        $mian_num += 1;
                        break;
                    case 3:
                        $fan_num += 1;
                        break;
                }

            }
        }
        Order::where(['order_sn'=>$order_sn])->update(['order_status'=>2]);
        //扣除库存
        Pickup::where(['id'=>$order['pickup_id']])->setDec('posts_num',$order['num']);
        Pickup::where(['id'=>$order['pickup_id']])->setDec('fan_num',$fan_num);
        Pickup::where(['id'=>$order['pickup_id']])->setDec('mian_num',$mian_num);
        Pickup::where(['id'=>$order['pickup_id']])->setDec('tang_num',$tang_num);
        //生成记录
        $addData = [
            'pickup_id'         =>      $order['pickup_id'],
            'posts_num'         =>      -$order['num'],
            'fan_num'           =>      -$fan_num,
            'mian_num'          =>      -$mian_num,
            'tang_num'          =>      -$tang_num,
            'desc'              =>      '订单核销',
            'type'              =>      2,
            'order_id'          =>      $order['id']
        ];
        Pickupstock::insert($addData);
        //查询该用户是否有上级
        $users = Users::getInfo(['id'=>$order['users_id']],'id,pid,is_grant');
        if($users['pid'] > 0 && $users['is_grant'] == 0){
            //查询已核销订单数
            $num1 = Order::where(['users_id'=>$users['id'],'order_status'=>'2'])->count();
            $num2 = Splicingorder::where(['users_id'=>$users['id'],'order_status'=>'3'])->count();
            if($num1 + $num2 >= 1){
                $bonus_num = Config::getValue(['name'=>'invitation']);
                //查询优惠券
                $bonus = Bonus::where(['id'=>1])->find();
                if(!empty($bonus) && $bonus_num>0){
                    //发放优惠券
                    $addData = [
                        'users_id'      =>      $users['pid'],
                        'bonus_id'      =>      $bonus['id'],
                        'num'           =>      $bonus_num,
                        'endtime'       =>      30*86400+time(),
                        'addtime'       =>      time(),
                        'type'          =>      4,
                        'order_id'      =>      $users['id']
                    ];
                    $bonusTempor = [
                        'users_id'      =>      $users['pid'],
                        'xid'           =>      $users['id'],
                        'type'          =>      0,
                        'bonus'         =>      json_encode($addData),
                        'addtime'       =>      time()
                    ];
                    db("bonus_tempor")->insert($bonusTempor);
                    Users::where(['id'=>$users['id']])->update(['is_grant'=>1]);
                }
            }
        }
        return_msg(0,'操作成功');
    }

    //拼单验单列表
    public function rider_splicing_pickup_list(){
        $where['status'] = '1';
        $where['rider_id'] = $this->userInfo['id'];
        $where['date'] = date("Y-m-d");
        $lists = Splicing::where($where)->field("id,address,num,addtime")->order('id desc')->select();
        foreach($lists as &$val){
            $val['addtime'] = date("Y-m-d H:i",$val['addtime']);
            $orderList = Splicingorder::where(['splicing_id'=>$val['id'],'order_status'=>['in',['1','2']]])->field('id,order_status,num,aux,name,phone')->select();
            foreach($orderList as &$v){
                //查询 面、饭、汤 份数
                $v['fan_num'] = 0;
                $v['mian_num'] = 0;
                $v['tang_num'] = 0;
                $aux = json_decode($v['aux'],true);
                foreach($aux as $v2){
                    foreach($v2 as $v3){
                        switch ($v3['id']){
                            case 1:
                                $v['tang_num'] += 1;
                                break;
                            case 2:
                                $v['mian_num'] += 1;
                                break;
                            case 3:
                                $v['fan_num'] += 1;
                                break;
                        }

                    }
                }
                unset($v['aux']);
            }
            $val['order_list'] = $orderList;
        }
        return_msg(0,'查询成功',$lists);
    }

    //拼单订单取货操作
    public function rider_splicing_pickup(){
        $id = input('id',0);    //订单ID
        $field = "id,users_id,order_sn,order_status,money";
        $order = Splicingorder::where(['id'=>$id])->field($field)->find();
        if(empty($order)){
            return_msg(1,'参数错误：订单不存在！');
        }
        if($order['order_status'] == 2){
            //更新状态
            return_msg(1,'该订单已取餐！');
        }
        if($order['order_status'] == 1){
            //更新状态
            Splicingorder::where(['id'=>$id])->update(['order_status'=>'2']);

            //查询该用户是否有上级
            $users = Users::getInfo(['id'=>$order['users_id']],'id,pid,is_grant');
            if($users['pid'] > 0 && $users['is_grant'] == 0){
                //查询已核销订单数
                $num1 = Order::where(['users_id'=>$users['id'],'order_status'=>'2'])->count();
                $num2 = Splicingorder::where(['users_id'=>$users['id'],'order_status'=>'3'])->count();
                if($num1 + $num2 >= 1){
                    $bonus_num = Config::getValue(['name'=>'invitation']);
                    //查询优惠券
                    $bonus = Bonus::where(['id'=>1])->find();
                    if(!empty($bonus) && $bonus_num>0){
                        //发放优惠券
                        $addData = [
                            'users_id'      =>      $users['pid'],
                            'bonus_id'      =>      $bonus['id'],
                            'num'           =>      $bonus_num,
                            'endtime'       =>      30*86400+time(),
                            'addtime'       =>      time(),
                            'type'          =>      4,
                            'order_id'      =>      $users['id']
                        ];
                        $bonusTempor = [
                            'users_id'      =>      $users['pid'],
                            'xid'           =>      $users['id'],
                            'type'          =>      0,
                            'bonus'         =>      json_encode($addData),
                            'addtime'       =>      time()
                        ];
                        db("bonus_tempor")->insert($bonusTempor);
                        Users::where(['id'=>$users['id']])->update(['is_grant'=>1]);
                    }
                }
            }

        }
        return_msg(0,'操作成功！');
    }
}
